package com.jhsw.roadsun.module.business.dal.mysql.useraddress;

import cn.hutool.core.util.StrUtil;
import com.jhsw.roadsun.framework.common.pojo.PageResult;
import com.jhsw.roadsun.framework.mybatis.core.mapper.BaseMapperX;
import com.jhsw.roadsun.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.jhsw.roadsun.framework.mybatis.core.query.MPJLambdaWrapperX;
import com.jhsw.roadsun.module.business.controller.admin.useraddress.vo.UserAddressPageReqVO;
import com.jhsw.roadsun.module.business.controller.app.useraddress.vo.AppUserAddressPageReqVO;
import com.jhsw.roadsun.module.business.controller.app.useraddress.vo.AppUserAddressRespVO;
import com.jhsw.roadsun.module.business.dal.dataobject.useraddress.UserAddressDO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

/**
 * 地址簿 Mapper
 *
 * @author Ysugar
 */
@Mapper
public interface UserAddressMapper extends BaseMapperX<UserAddressDO> {

    default PageResult<UserAddressDO> selectPage(UserAddressPageReqVO reqVO) {
        return selectPage(reqVO, new LambdaQueryWrapperX<UserAddressDO>()
                .eqIfPresent(UserAddressDO::getUserId, reqVO.getUserId())
                .likeIfPresent(UserAddressDO::getName, reqVO.getName())
                .eqIfPresent(UserAddressDO::getType, reqVO.getType())
                .eqIfPresent(UserAddressDO::getIsNormal, reqVO.getIsNormal())
                .betweenIfPresent(UserAddressDO::getCreateTime, reqVO.getCreateTime())
                .orderByDesc(UserAddressDO::getId));
    }

    default PageResult<AppUserAddressRespVO> appGetUserAddressPage(AppUserAddressPageReqVO reqVO, Long userId){
        String search = reqVO.getSearch();
        return selectJoinPage(reqVO, AppUserAddressRespVO.class, new MPJLambdaWrapperX<UserAddressDO>()
                .selectAll(UserAddressDO.class)
                .eqIfPresent(UserAddressDO::getUserId, userId)
                .eqIfPresent(UserAddressDO::getType, reqVO.getType())
                .nested(StrUtil.isNotEmpty(search),
                        o -> o.like(UserAddressDO::getName, search)
                                .or().like(UserAddressDO::getMobile, search)
                                .or().like(UserAddressDO::getAddress, search))
                .orderByDesc(UserAddressDO::getId));
    }

    @Select("select count(1) from business_user_address bua where bua.deleted = 0 and bua.user_id = #{param1} and bua.`type` = #{param2}")
    Long selectCountByUserId(Long userId, int type);
}